<?php

namespace App\EventListener;

use App\Utils\Annotation\ApiAuthority;
use App\Utils\Helper\ApiHelper;
use App\Utils\Helper\GeneralHelper;
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class ApiAuthorityListener {
    private $annotationReader;

    public function __construct () {
        $this->annotationReader = new AnnotationReader();
    }

    public function onKernelController (ControllerEvent $event): void {
        if (!$event->isMasterRequest()) {
            return;
        }

        $controllers = $event->getController();
        if (!is_array($controllers)) {
            return;
        }

        // 校验用户
        $admin_user = ApiHelper::getAdminUser();
        if (!is_object($admin_user)) {
            return;
        }

        // 校验权限
        $authority = ApiHelper::getInstance()->getAuthority();
        if ($authority instanceof ApiAuthority) {
            $admin_modules = GeneralHelper::getInstance()->getModulesByAdminUserGroupId($admin_user->getAdminUserGroupId());
            if (!in_array($authority->need, $admin_modules)) {
                access_denied_exception();
            }
        }
    }
}